<?php
class Project extends AppModel
{
    public $name = 'Project';
    public $displayField = 'name';
    public $actsAs = array(
        'Sluggable' => array(
            'label' => array(
                'name'
            )
        ) ,
        'SuspiciousWordsDetector' => array(
            'fields' => array(
                'name',
                'short_description',
                'description'
            )
        ) ,
        'Logable' => array(
            'userModel' => 'User',
            'userKey' => 'user_id'
        ) ,
        'Aggregatable'
    );
    var $aggregatingFields = array(
        'embed_view_count' => array(
            'mode' => 'real',
            'key' => 'project_id',
            'foreignKey' => 'project_id',
            'model' => 'ProjectView',
            'function' => 'COUNT(ProjectView.project_id)',
            'conditions' => array(
                'ProjectView.project_view_type_id' => 2
            )
        ) ,
    );
    //$validate set in __construct for multi-language support
    //The Associations below have been created with all possible keys, those that are not needed can be removed
    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'counterCache' => true,
            'counterScope' => array(
                'admin_suspend' => '0',
	         ) ,

        ) ,
        'ProjectStatus' => array(
            'className' => 'ProjectStatus',
            'foreignKey' => 'project_status_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'counterCache' => true,
        ) ,
        'PledgeType' => array(
            'className' => 'PledgeType',
            'foreignKey' => 'pledge_type_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'counterCache' => false,
        ) ,
        'ProjectCategory' => array(
            'className' => 'ProjectCategory',
            'foreignKey' => 'project_category_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'counterCache' => true,
            'counterScope' => array(
                'is_active' => 1,
                'admin_suspend' => '0',
                'project_status_id' => array(ConstProjectStatus::OpenForIdea,ConstProjectStatus::OpenForFunding,ConstProjectStatus::ReserveAmountReached),
            )
        ) ,
        'City' => array(
            'className' => 'City',
            'foreignKey' => 'city_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'counterCache' => true,
            'counterScope' => array(
                'is_active' => 1,
                'admin_suspend' => '0',
                'project_status_id' => array(ConstProjectStatus::OpenForIdea,ConstProjectStatus::OpenForFunding,ConstProjectStatus::ReserveAmountReached),
            )
        ) ,
        'State' => array(
            'className' => 'State',
            'foreignKey' => 'state_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ) ,
        'Country' => array(
            'className' => 'Country',
            'foreignKey' => 'country_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ) ,
		'Ip' => array(
            'className' => 'Ip',
            'foreignKey' => 'ip_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'counterCache' => true
        )
    );
    public $hasOne = array(
        'Attachment' => array(
            'className' => 'Attachment',
            'foreignKey' => 'foreign_id',
            'dependent' => true,
            'conditions' => array(
                'Attachment.class' => 'Project',
            ) ,
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
    );
    public $hasMany = array(
        'ProjectComment' => array(
            'className' => 'ProjectComment',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'ProjectFeed' => array(
            'className' => 'ProjectFeed',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'Blog' => array(
            'className' => 'Blog',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'ProjectView' => array(
            'className' => 'ProjectView',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'ProjectFlag' => array(
            'className' => 'ProjectFlag',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'ProjectFund' => array(
            'className' => 'ProjectFund',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'ProjectFollower' => array(
            'className' => 'ProjectFollower',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'ProjectReward' => array(
            'className' => 'ProjectReward',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'ProjectRating' => array(
            'className' => 'ProjectRating',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'Message' => array(
            'className' => 'Message',
            'foreignKey' => 'project_id',
            'dependent' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'Activity' => array(
            'className' => 'Activity',
            'foreignKey' => 'model_id',
            'dependent' => true,
            'conditions' => array(
                'Activity.model' => 'Project'
            ) ,
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'Transaction' => array(
            'className' => 'Transaction',
            'foreignKey' => 'foreign_id',
            'dependent' => true,
            'conditions' => array(
                'Transaction.class' => 'Project'
            ) ,
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
		'ProjectMedia' => array(
            'className' => 'Attachment',
            'foreignKey' => 'foreign_id',
            'dependent' => true,
            'conditions' => array(
                'ProjectMedia.class =' => 'ProjectMedia'
            ) ,
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
    );
    function __construct($id = false, $table = null, $ds = null)
    {
        parent::__construct($id, $table, $ds);
        $this->validate = array(
            'name' => array(
                'rule' => 'notempty',
                'allowEmpty' => false,
                'message' => __l('Required')
            ) ,
			'address' => array(
                'rule' => 'notempty',
                'allowEmpty' => false,
                'message' => __l('Required')
            ) ,
			'address1' => array(
                'rule' => 'notempty',
                'allowEmpty' => false,
                'message' => __l('Required')
            ) ,
            'short_description' => array(
                'rule2' => array(
                    'rule' => array(
                        'between',
                        Configure::read('Project.min_short_description_length') ,
                        Configure::read('Project.project_short_description_length') ,
                    ) ,
                    'allowEmpty' => false,
                    'message' => sprintf(__l('Short description between %s to %s characters'), Configure::read('Project.min_short_description_length'), Configure::read('Project.project_short_description_length'))
                ) ,
                'rule1' => array(
                    'rule' => 'notempty',
                    'allowEmpty' => false,
                    'message' => __l('Required')
                )
            ) ,
            'user_id' => array(
                'rule' => 'numeric',
                'allowEmpty' => false,
                'message' => __l('Required')
            ) ,
            'needed_amount' => array(
                'rule4' => array(
                    'rule' => '_reservedAmount',
                    'message' => 'Needed amount should be greater then reserve amount.'
                ) ,
                'rule3' => array(
                    'rule' => array(
                        'minMaxAmount',
                        'needed_amount',
                    ) ,
                    'message' => sprintf(__l('The amount between %s to %s'), Configure::read('Project.minimum_amount'), Configure::read('Project.maximum_amount'))
                ) ,
                'rule2' => array(
                    'rule' => array(
                        'comparison',
                        '>=',
                        1
                    ) ,
                    'allowEmpty' => false,
                    'message' => __l('Must be greater than zero')
                ) ,
                'rule1' => array(
                    'rule' => 'notempty',
                    'allowEmpty' => false,
                    'message' => __l('Required')
                )
            ) ,
            'project_funding_end_date' => array(
                'rule3' => array(
                    'rule' => array(
                        'projectFundingEndDate',
                        'project_funding_end_date',
                    ) ,
                    'message' => __l('Project funding end date should not be greater than paypal expiry date')
                ) ,
                'rule2' => array(
                    'rule' => array(
                        'comparison',
                        '>=',
                        date('Y-m-d') ,
                    ) ,
                    'message' => __l('Project funding end date should  be greater than to today')
                ) ,
                'rule1' => array(
                    'rule' => 'date',
                    'message' => __l('Enter valid date')
                )
            ) ,
            'expected_delivery_date' => array(
                'rule2' => array(
                    'rule' => array(
                        'fundingEndDate',
                        'project_funding_end_date',
                        'project_status_id'
                    ) ,
                    'message' => __l('Expected delivery date should be future date')
                ) ,
                'rule1' => array(
                    'rule' => 'date',
                    'message' => __l('Enter valid date')
                )
            ) ,
            'project_status_id' => array(
                'rule1' => array(
                    'rule' => 'numeric',
                    'allowEmpty' => false,
                    'message' => __l('Required')
                )
            ) ,
            'project_category_id' => array(
                'rule1' => array(
                    'rule' => 'notempty',
                    'allowEmpty' => false,
                    'message' => __l('Required')
                )
            ) ,
            'country_id' => array(
                'rule1' => array(
                    'rule' => 'notempty',
                    'allowEmpty' => false,
                    'message' => __l('Required')
                )
            ) ,
            'linkedin_url' => array(
                'rule1' => array(
                    'rule' => array(
                        'url',
						true
                    ) ,
                    'message' => __l('Must be a valid URL, starting with http://') ,
                    'allowEmpty' => true
                )
            ) ,
            'facebook_url' => array(
                'rule1' => array(
                    'rule' => array(
                        'url',
						true
                    ) ,
                    'message' => __l('Must be a valid URL, starting with http://') ,
                    'allowEmpty' => true
                )
            ) ,
            'twitter_url' => array(
                'rule1' => array(
                    'rule' => array(
                        'url',
						true
                    ) ,
                    'message' => __l('Must be a valid URL, starting with http://') ,
                    'allowEmpty' => true
                )
            ) ,
            'youtube_url' => array(
                'rule1' => array(
                    'rule' => array(
                        'url',
						true
                    ) ,
                    'message' => __l('Must be a valid URL, starting with http://') ,
                    'allowEmpty' => true
                )
            ) ,
            'myspace_url' => array(
                'rule1' => array(
                    'rule' => array(
                        'url',
						true
                    ) ,
                    'message' => __l('Must be a valid URL, starting with http://') ,
                    'allowEmpty' => true
                )
            ) ,
            'imdb_url' => array(
                'rule1' => array(
                    'rule' => array(
                        'url',
						true
                    ) ,
                    'message' => __l('Must be a valid URL, starting with http://') ,
                    'allowEmpty' => true
                )
            ) ,
            'min_amount_to_fund' => array(
                'rule1' => array(
                    'rule' => '_checkRewardAmount',
                    'allowEmpty' => false,
                    'message' => __l('Required') ,
                ) ,
            ) ,
            'is_agree_terms_conditions' => array(
                'rule' => array(
                    'equalTo',
                    '1'
                ) ,
                'message' => __l('You must agree to the terms and policies')
            ) ,
            'video_embed_url' => array(
                'rule1' => array(
                    'rule' => array(
                        '_validateVideoUrl'
                    ) ,
                    'message' => __l('Must be a valid video embed URL') ,
                    'allowEmpty' => true
                )
            ) ,
            'feed_url' => array(
                'rule1' => array(
                    'rule' => array(
                        'url',
						true
                    ) ,
                    'message' => __l('Must be a valid URL, starting with http://') ,
                    'allowEmpty' => true
                )
            ) ,
            'facebook_feed_url' => array(
                'rule1' => array(
                    'rule' => array(
                        'url',
						true
                    ) ,
                    'message' => __l('Must be a valid URL, starting with http://') ,
                    'allowEmpty' => true
                )
            ) ,
            'reserve_amount' => array(
                'rule3' => array(
                    'rule' => array(
                        'comparison',
                        '>=',
                        Configure::read('Project.minimum_amount')
                    ) ,
                    'allowEmpty' => true,
                    'message' => __l('Reserve amount must be greater than ') . Configure::read('Project.minimum_amount')
                ) ,
                'rule2' => array(
                    'rule' => array(
                        'comparison',
                        '>=',
                        1
                    ) ,
                    'allowEmpty' => true,
                    'message' => __l('Must be greater than zero')
                ) ,
                'rule1' => array(
                    'rule' => 'notempty',
                    'allowEmpty' => true,
                    'message' => __l('Required')
                )
            ) ,
        );
        
        $this->isFilterOptions = array(
            ConstMoreAction::Suspend => __l('Suspend') ,
            ConstMoreAction::Flagged => __l('Flag')
        );
        $this->moreActions = array(
            ConstMoreAction::Approved => __l('Open') ,
            ConstMoreAction::Active => __l('Active') ,
            ConstMoreAction::Inactive => __l('Inactive') ,
            ConstMoreAction::Suspend => __l('Suspend') ,
            ConstMoreAction::Unsuspend => __l('Unsuspend') ,
            ConstMoreAction::Flagged => __l('Flag') ,
            ConstMoreAction::Unflagged => __l('Clear flag') ,
            ConstMoreAction::Delete => __l('Delete')
        );
    }
    function _checkRewardAmount()
    {
        if ($this->data[$this->name]['pledge_type_id'] != ConstPledgeTypes::Any) {
            if ($this->data[$this->name]['min_amount_to_fund'] < 1 && ($this->data[$this->name]['pledge_type_id'] == ConstPledgeTypes::Minimum || $this->data[$this->name]['pledge_type_id'] == ConstPledgeTypes::Fixed || $this->data[$this->name]['pledge_type_id'] == ConstPledgeTypes::Multiple)) {
                $this->validationErrors['min_amount_to_fund'] = __l('Must be greater than zero');
                return true;
            } else if ($this->data[$this->name]['min_amount_to_fund'] > $this->data[$this->name]['needed_amount'] && ($this->data[$this->name]['pledge_type_id'] == ConstPledgeTypes::Minimum || $this->data[$this->name]['pledge_type_id'] == ConstPledgeTypes::Fixed || $this->data[$this->name]['pledge_type_id'] == ConstPledgeTypes::Multiple)) {
                $this->validationErrors['min_amount_to_fund'] = __l('The amount should be less than needed amount');
                return true;
            } else if ($this->data[$this->name]['needed_amount'] % $this->data[$this->name]['min_amount_to_fund'] != 0 && ($this->data[$this->name]['pledge_type_id'] == ConstPledgeTypes::Multiple || $this->data[$this->name]['pledge_type_id'] == ConstPledgeTypes::Fixed) && !$this->data[$this->name]['is_allow_over_funding']) {
                $this->validationErrors['min_amount_to_fund'] = __l('Amount cannot be equally shared or else you should allow over funding.');
                return true;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
    function _reservedAmount()
    {
        if (!empty($this->data[$this->name]['needed_amount']) && Configure::read('Project.is_enable_threshold_limit') == 1 && $this->data[$this->name]['reserve_amount'] >= $this->data[$this->name]['needed_amount']) {
            return false;
        }
        return true;
    }
    function minMaxAmount($field1, $field = null)
    {
        return ($this->data[$this->name][$field] >= Configure::read('Project.minimum_amount') && $this->data[$this->name][$field] <= Configure::read('Project.maximum_amount'));
    }
    function fundingEndDate($fields, $field1, $field2)
    {
        if ($this->data[$this->name][$field2] == ConstProjectStatus::OpenForFunding) {
            if (Date('Y') . '-' . Date('m') . '-' . Date('d') <= $this->data[$this->name][$field1]) {
                return true;
            }
        } else {
            return true;
        }
    }
    function projectFundingEndDate($fields, $field1)
    {
        if (!empty($this->data[$this->name][$field1])) {
            if (!empty($this->data[$this->name]['project_funding_start_date'])) {
                $start_date = strtotime($this->data[$this->name]['project_funding_start_date']);
            } else {
                $start_date = time();
            }
            if ($this->data[$this->name][$field1] <= date('Y-m-d', mktime(0, 0, 0, date('m') , (date('d', $start_date) + Configure::read('Project.paypal_expiry_date')) , date('Y')))) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    function isValidDate($field1, $field = null)
    {
        return Date('Y') . '-' . Date('m') . '-' . Date('d') <= $this->data[$this->name][$field];
    }
    function isValiedEndDate($field3, $field1 = null, $field2 = null)
    {
        return $this->data[$this->name][$field1] <= $this->data[$this->name][$field2];
    }
	function _validateVideoUrl()
    {
        App::import('Helper', 'Embed');
        $this->Embed = new EmbedHelper();
        if (!(!empty($this->data['Project']['video_embed_url']) && $this->Embed->parseUrl($this->data['Project']['video_embed_url']))) {
            return false;
        }
        return true;
    }
    function processProjectStatus($project_id)
    {
        $project = $this->find('first', array(
            'conditions' => array(
                'Project.id' => $project_id
            ) ,
            'recursive' => 2,
            'contain' => array(
                'ProjectFund'
            )
        ));
        if (!empty($project)) {
            //handle tipped status
            if ($project['Project']['needed_amount'] <= $project['Project']['collected_amount']) {
                $this->processFundStatus($project);
            } else {
                $this->_closeProjects($project);
            }
        }
    }
    function getImageUrl($model, $attachment, $options)
    {
        $default_options = array(
            'dimension' => 'big_thumb',
            'class' => '',
            'alt' => 'alt',
            'title' => 'title',
            'type' => 'jpg'
        );
        $options = array_merge($default_options, $options);
        $image_hash = $options['dimension'] . '/' . $model . '/' . $attachment['id'] . '.' . md5(Configure::read('Security.salt') . $model . $attachment['id'] . $options['type'] . $options['dimension'] . Configure::read('site.name')) . '.' . $options['type'];
        return Cache::read('site_url_for_shell', 'long') . 'img/' . $image_hash;
    }
    function _refund($project_id)
    {
        $project = $this->find('first', array(
            'conditions' => array(
                'Project.id' => $project_id
            ) ,
            'contain' => array(
                'ProjectFund' => array(
                    'conditions' => array(
                        'ProjectFund.is_paid' => 0,
                        'ProjectFund.is_refunded = ' => 0,
                        'ProjectFund.is_cancelled = ' => 0
                    ) ,
                    'fields' => array(
                        'ProjectFund.id',
                    )
                )
            ) ,
            'fields' => array(
                'Project.id'
            ) ,
            'recuesive' => 0
        ));
        App::import('Model', 'Payment');
        $this->Payment = new Payment();
        if (!empty($project['ProjectFund'])) {
            foreach($project['ProjectFund'] as $project_fund) {
                $return = $this->Payment->refundProjectFund($project_fund['id']);
            }
        }
        $this->Behaviors->detach('Logable');
        $this->updateAll(array(
            'Project.collected_amount' => 0,
            'Project.collected_percentage' => 0,
        ) , array(
            'Project.id' => $project_id
        ));
    }
    function _executepay($project_id)
    {
        $this->Behaviors->detach('Logable');
        $project = $this->find('first', array(
            'conditions' => array(
                'Project.id' => $project_id
            ) ,
            'contain' => array(
                'ProjectFund' => array(
                    'conditions' => array(
                        'ProjectFund.is_paid' => 0,
                        'ProjectFund.is_refunded = ' => 0,
                        'ProjectFund.is_cancelled = ' => 0
                    ) ,
                    'fields' => array(
                        'ProjectFund.id',
                    )
                )
            ) ,
            'fields' => array(
                'Project.id'
            ) ,
            'recuesive' => 0
        ));
        App::import('Model', 'Payment');
        $this->Payment = new Payment();
        if (!empty($project['ProjectFund'])) {
            foreach($project['ProjectFund'] as $project_fund) {
                $return = $this->Payment->executeProjectFund($project_fund['id']);
            }
        }
    }
    
  
    function rss_feed($url_array = null, $limit = null)
    {
        App::import('Vendor', 'simplepie');
        $feed = new SimplePie();
        if (!empty($limit)) {
            $feed->set_item_limit($limit);
        }
        $feed->set_feed_url($url_array);
        $feed->set_cache_location(CACHE . 'rss' . DS);
        $feed->set_cache_duration(300);
        $feed->set_timeout(30);
        $feed->set_favicon_handler(Cache::read('site_url_for_shell', 'long') . 'handler_image.php');
        //retrieve the feed
        $feed->init();
        $feed->handle_content_type();
        return $feed;
    }
    function _updateCityProjectCount()
    {
        $cityProjects = $this->City->find('all', array(
            'conditions' => array(
                'City.is_approved' => 1,
            ) ,
            'contain' => array(
                'Project' => array(
                    'conditions' => array(
						'Project.project_status_id' => array(
							ConstProjectStatus::OpenForFunding,
							ConstProjectStatus::GoalReached,
							ConstProjectStatus::ReserveAmountReached
                        ) ,
						'Project.is_active' => 1
                    ) ,
                    'fields' => array(
                        'Project.id',
                    ) ,
                ) ,
            ) ,
            'recuesive' => 0
        ));
        $this->City->updateAll(array(
            'City.project_count' => 0,
        ));
        foreach($cityProjects as $cityProject) {
            if (!empty($cityProject['Project'])) {
                $this->City->updateAll(array(
                    'City.project_count' => count($cityProject['Project']) ,
                ) , array(
                    'City.id' => $cityProject['City']['id']
                ));
            }
        }
    }
}
?>